<template>
  <div class="publish-page">
    <div class="container">
      <template v-if="!showSuccess">
        <div class="publish-card">
          <h2>发布骗子信息</h2>
          <el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="handleSubmit">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" maxlength="50" show-word-limit />
            </el-form-item>

            <el-form-item label="骗子手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>

            <el-form-item label="详细描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="6" placeholder="请详细描述被骗经过..." maxlength="1000"
                show-word-limit />
            </el-form-item>

            <el-form-item label="证据材料">
              <el-upload
                v-model:file-list="fileList"
                :action="`${API_BASE_URL}/upload`"
                :headers="{ Authorization: `Bearer ${userStore.token}` }"
                list-type="picture-card"
                accept="image/*"
                :on-preview="handlePictureCardPreview"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                multiple
                :limit="5"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg/png文件，且不超过5MB
                  </div>
                </template>
              </el-upload>

              <el-dialog v-model="dialogVisible" title="预览">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="submitting" class="submit-btn">
                发布
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <div v-else class="success-card">
        <div class="success-content">
          <img
            src="https://cdn.jsdelivr.net/gh/Tarikul-Islam-Anik/Animated-Fluent-Emojis/Emojis/Smilies/Star-Struck.png"
            class="success-icon"
            alt="success"
          />
          <h2>发布成功！</h2>
          <p>您的信息已成功发布到骗子列表中。</p>
          <div class="success-actions">
            <el-button type="primary" @click="handleContinue">继续发布</el-button>
            <el-button @click="router.push('/scam-list')">查看列表</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { scams } from '../api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import API_BASE_URL from '../config/api'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const submitting = ref(false)
const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const showSuccess = ref(false)

const form = reactive({
  title: '',
  phone: '',
  description: '',
  evidence: []
})

const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号码'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在5-50个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入详细描述', trigger: 'blur' },
    { min: 50, max: 1000, message: '描述长度应在50-1000个字符之间', trigger: 'blur' }
  ]
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file, fileList) => {
  form.evidence = fileList.map(file => file.response?.url || file.url)
}

const handleSuccess = (response, file, fileList) => {
  form.evidence = fileList.map(file => file.response?.url || file.url)
  ElMessage.success('上传成功')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 确保获取正确的图片URL
    const evidence = fileList.value.map(file => file.response?.url || file.url).filter(Boolean)

    await scams.create({
      ...form,
      evidence
    })

    showSuccess.value = true
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '发布失败')
    } else {
      ElMessage.error('发布失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

const handleContinue = () => {
  showSuccess.value = false
  form.title = ''
  form.phone = ''
  form.description = ''
  form.evidence = []
  fileList.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<style scoped>
.publish-page {
  padding: 2rem 0;
}

.publish-card {
  max-width: 800px;
  margin: 0 auto;
  background-color: var(--text-light);
  border-radius: var(--border-radius);
  padding: 2rem;
  box-shadow: var(--box-shadow);
}

.publish-card h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: var(--primary-color);
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
}

.el-upload__tip {
  color: #666;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

.success-card {
  max-width: 600px;
  margin: 0 auto;
  background-color: var(--text-light);
  border-radius: var(--border-radius);
  padding: 3rem 2rem;
  box-shadow: var(--box-shadow);
  text-align: center;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
}

.success-icon {
  width: 96px;
  height: 96px;
}

.success-content h2 {
  color: #67C23A;
  font-size: 1.8rem;
  margin: 0;
}

.success-content p {
  color: #606266;
  font-size: 1.1rem;
  margin: 0;
}

.success-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

@media (max-width: 768px) {
  .publish-card {
    margin: 1rem;
    padding: 1.5rem;
  }

  .success-card {
    margin: 1rem;
    padding: 2rem 1.5rem;
  }

  .success-icon {
    width: 80px;
    height: 80px;
  }

  .success-content h2 {
    font-size: 1.5rem;
  }

  .success-content p {
    font-size: 1rem;
  }
}
</style>